﻿using System;
using System.Collections.Generic;
using System.Text;
using Outlook = Microsoft.Office.Interop.Outlook;
using Office = Microsoft.Office.Core;

namespace Pst_Backup_2013
{
    public partial class ThisAddIn
    {
        System.Windows.Forms.Timer _timer = new System.Windows.Forms.Timer();
        List<string> _removedStores = new List<string>();

        /// <summary>
        /// This method is call when the AddIn start.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            ((Outlook.ApplicationEvents_11_Event)Application).Quit += ThisAddIn_Quit;
            //this._timer.Interval = 15000;
            //this._timer.Tick += PerformOpportunisticBackup;
            //this._timer.Start();
        }

        private void PerformOpportunisticBackup(object sender, EventArgs e)
        {
            this._timer.Stop();

            if (this._removedStores.Count == 0)
            {
                try
                {
                    Outlook.Stores stores = new Outlook.Application().Session.Stores;
                    foreach (Outlook.Store store in stores)
                    {
                        try
                        {
                            if (!String.IsNullOrEmpty(store.FilePath) && store.IsDataFileStore && !store.IsCachedExchange)
                            {
                                System.Windows.Forms.MessageBox.Show("Removing " + store.DisplayName);
                                Application.Session.RemoveStore(store.GetRootFolder());
                                this._removedStores.Add(store.FilePath);
                            }
                        }
                        catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); }
                    }
                }
                catch (Exception ex)
                {
                    Utilities.LogEvent(20001, "Unable to enumerate PST files.\r\n" + ex.Message, System.Diagnostics.EventLogEntryType.Error);
                }
                this._timer.Start();
            }
            else
            {
                foreach (string store in this._removedStores)
                {
                    try
                    {
                        Application.Session.AddStore(store);
                    }
                    catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); }
                }

            }
        }

        /// <summary>
        /// This method is call when Outlook is closing.
        /// </summary>
        private void ThisAddIn_Quit()
        {
            string currentPath = String.Empty;

            try
            {
                Utilities.UpdateRegistryEntries();
                Microsoft.Win32.RegistryKey baseKey64 = null;
                try
                {
                    baseKey64 = Microsoft.Win32.RegistryKey.OpenBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, Microsoft.Win32.RegistryView.Registry64);
                    if (baseKey64 != null)
                        baseKey64 = baseKey64.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Pst Backup 2013", false);
                }
                catch (Exception) { }

                Microsoft.Win32.RegistryKey baseKey32 = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\Pst Backup 2013", false);

                if (baseKey32 != null)
                    currentPath = (string)baseKey32.GetValue("InstallLocation");
                else
                    currentPath = (string)baseKey64.GetValue("InstallLocation");
                //System.Windows.Forms.MessageBox.Show(currentPath);
                //System.Diagnostics.Process.Start(@"C:\Users\Courtel\Documents\Visual Studio 2013\Projects\Pst-Backup-2013\Pst-Backup-Agent\bin\Debug\Pst-Backup-Agent.exe", "-save");
                System.Diagnostics.Process.Start(currentPath + "Pst-Backup-Agent.exe", "-save");
            }
            catch (Exception ex)
            {
                Utilities.LogEvent(20000, "Unable to start " + currentPath + "Pst-Backup-Agent.exe" + "\r\n" + ex.Message, System.Diagnostics.EventLogEntryType.Error);
            }
        }
        
        #region Code généré par VSTO

        /// <summary>
        /// Méthode requise pour la prise en charge du concepteur - ne modifiez pas
        /// le contenu de cette méthode avec l'éditeur de code.
        /// </summary>
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(ThisAddIn_Startup);
        }

        #endregion
    }
}
